package com.wiiss.ams.ding;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.wiiss.ams.util.http.HttpRequest;
import com.wiiss.ams.util.http.HttpUtil;
import com.wiiss.ams.util.Const;
import com.wiiss.ams.util.Id;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import static cn.hutool.http.Header.CONNECTION;
import static cn.hutool.http.Header.CONTENT_TYPE;

public class AmsMsgSender {

    private static final String URL = "http://10.90.199.44:5804/api/AGVAlarmSend/HandleSendAlarm";

    public static JSONObject send(String alarmId, String alarmTitle, String alarmType, String alarmContent, JSONObject staff) {
        Long id = Id.next();

        JSONObject body = new JSONObject().set("amsId", id)
                .set("deviceId", "HC01")
                .set("personNum", staff.get("no"))
                .set("personName", staff.get("name"))
                .set("department", staff.get("department"))
                .set("msgId", alarmId)
                .set("alarmTitle", alarmTitle)
                .set("alarmType", alarmType)
                .set("alarmDesc", alarmContent)
                .set("alarmTime", Const.DATE_TIME_FORMATTER.format(LocalDateTime.now()));

        parseHttpResponse(HttpUtil.request(
                new HttpRequest(Method.POST, URL, new HashMap<>(Map.of(CONNECTION.getValue(), "keep-alive", CONTENT_TYPE.getValue(), "application/json;charset=UTF-8")), body)));
        return new JSONObject().set("id", id)
                .set("alarmId", alarmId)
                .set("alarmTitle", alarmTitle)
                .set("alarmType", alarmType)
                .set("alarmContent", alarmContent)
                .set("staffNo", staff.get("no"));
    }

    /**
     * 将服务器返回规范化
     * @author 52291590 2023年6月12日 下午3:37:37
     */
    private static JSONObject parseHttpResponse(HttpResponse response) {
        // 视为网络错误
        if (response.getStatus() != 200) {
            throw new HttpException("request failed, status: {}, body: {} ", response.getStatus(), response.body());
        }

        JSONObject jsonObject = null;

        String responseBody = response.body();
        if (JSONUtil.isTypeJSONObject(responseBody)) {
            jsonObject = new JSONObject(responseBody);
            if (!jsonObject.getStr("code").equals("200")) {
                throw new HttpException("request successfully, but response is not expected, response: {} ", responseBody);
            }
        } else {
            jsonObject = new JSONObject().set("data", JSONUtil.isTypeJSONArray(responseBody) ? new JSONArray(responseBody) : responseBody);
        }

        return jsonObject;
    }

    private AmsMsgSender() {
        super();
    }

}
